<?php

namespace App\Models\Common;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Log;

/**
 * Class MyOffice
 *
 * @package App\Models\Common
 * @Date:2022/8/3
 * @Author: Rudy
 *
 * 说明：
 * 1.如果操作的是word，则setSource(),loadWord(),addWaterMark(),addTexts(),saveOffice()
 * 2.如果操作的是ppt，则setSource(),pptToImg()
 */
class MyOffice extends Model
{
    private $source;
    private $phpWord;

    public function getContentString() {
        $phpWord = $this->phpWord;
        $html = '';
        foreach ($phpWord->getSections() as $section) {
            foreach ($section->getElements() as $ele1) {
                if ($ele1 instanceof \PhpOffice\PhpWord\Element\TextRun) {
                    foreach ($ele1->getElements() as $k=>$ele2) {
                        if ($ele2 instanceof \PhpOffice\PhpWord\Element\Text) {
                            $html .= mb_convert_encoding($ele2->getText(), 'GBK', 'UTF-8');
                        } elseif ($ele2 instanceof \PhpOffice\PhpWord\Element\Image) {
                            /*$imageSrc = 'images/' . md5($ele2->getSource()) . '.' . $ele2->getImageExtension();
                            $imageData = $ele2->getImageStringData(true);
                            $imageData = 'data:' . $ele2->getImageType() . ';base64,' . $imageData;
                            file_put_contents($imageSrc, base64_decode($imageData));
                            $html .= '<img src="'. $imageSrc .'" style="width:100%;height:auto">';*/
                        }
                    }
                }

            }
        }
        return mb_convert_encoding($html, 'UTF-8', 'GBK');
    }

    public function getContentWithHtml() {
        $phpWord = $this->phpWord;
        $html = '';
        foreach ($phpWord->getSections() as $section) {
            foreach ($section->getElements() as $ele1) {
                $paragraphStyle = $ele1->getParagraphStyle();
                if ($paragraphStyle) {
                    $html .= '<p style="text-align:'. $paragraphStyle->getAlignment() .';text-indent:20px;">';
                } else {
                    $html .= '<p>';
                }
                if ($ele1 instanceof \PhpOffice\PhpWord\Element\TextRun) {
                    foreach ($ele1->getElements() as $k=>$ele2) {
                        if ($ele2 instanceof \PhpOffice\PhpWord\Element\Text) {
                            //$html .= mb_convert_encoding($ele2->getText(), 'GBK', 'UTF-8');
                            $style = $ele2->getFontStyle();
                            $fontFamily = mb_convert_encoding($style->getName(), 'GBK', 'UTF-8');
                            $fontSize = $style->getSize();
                            $isBold = $style->isBold();
                            $styleString = '';
                            $fontFamily && $styleString .= "font-family:{$fontFamily};";
                            $fontSize && $styleString .= "font-size:{$fontSize}px;";
                            $isBold && $styleString .= "font-weight:bold;";
                            $html .= sprintf('<span style="%s">%s</span>',
                                $styleString,
                                mb_convert_encoding($ele2->getText(), 'GBK', 'UTF-8')
                            );
                        } elseif ($ele2 instanceof \PhpOffice\PhpWord\Element\Image) {
                            $imageSrc = 'images/' . md5($ele2->getSource()) . '.' . $ele2->getImageExtension();
                            $imageData = $ele2->getImageStringData(true);
                            $imageData = 'data:' . $ele2->getImageType() . ';base64,' . $imageData;
                            file_put_contents($imageSrc, base64_decode($imageData));
                            $html .= '<img src="'. $imageSrc .'" style="width:100%;height:auto">';
                        }
                    }
                }elseif ($ele1 instanceof \PhpOffice\PhpWord\Element\Table) {
                    foreach ($ele1->getRows() as $ele)
                    {
                        //Log::info(self::getTableNode($ele));
                        $html .='<div>'.self::getTableNode($ele).'</div>';
                    }
                }
                $html .= '</p>';
            }
        }
        return mb_convert_encoding($html, 'UTF-8', 'GBK');
    }


    public function setSource($source) {
        //$this->source = iconv('utf-8', 'GBK', $source);
        $this->source = mb_convert_encoding($source,'GBK','utf-8');
    }

    public function loadWord() {
        $this->phpWord = \PhpOffice\PhpWord\IOFactory::load($this->source);
        //$this->phpWord->setDefaultParagraphStyle(['lineHeight'=>1.5]);
        $section =  $this->phpWord->getSection(0);

    }

    public function addWaterMark($waterMarkPath,$marginTo=0,$marginLeft=0,$width=100,$height=25){
        $section = $this->phpWord->getSection(0);
        $header = $section->createHeader();
        $header->addWatermark($waterMarkPath, compact('marginTo','marginLeft','width','height'));
    }

    public function addTexts(array $texts,$size=18,$name='宋体',$bold=true,$color='red') {
        $section = $this->phpWord->getSection(0);
        foreach ($texts as $text) {
            $section->addTextRun()->addText($text,compact('size','name','bold','color'));
        }
    }

    public function addImg($src,$marginTo=0,$marginLeft=0,$width=300,$height=200) {
        $section = $this->phpWord->getSection(0);
        $section->addImage($src,compact('width','height','marginTo','marginLeft'));
    }

    public function saveOffice($fileName) {
        $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($this->phpWord, 'Word2007');
        $objWriter->save($fileName);
    }

    public function pptToImg($exportFolder, $width=600, $height=400) {


        $powerpnt = new \COM("powerpoint.application") or die("Unable to instantiate Powerpoint");
        $presentation = $powerpnt->Presentations->Open($this->source, false, false, false) or die("Unable to open presentation");

        foreach($presentation->Slides as $k=>$slide) {
            if($k>9)break;
            //文件名，同一个附件重复则覆盖
            $slideName = $slide->SlideNumber;
            if (!file_exists($exportFolder)) mkdir($exportFolder, 0777, true);
            //保存到本地
            //dd($this->source,$exportFolder);
            $imagePath = $exportFolder.$slideName.".jpg";
            $imagePath = iconv('utf-8', 'GBK', $imagePath);
            if(!file_exists($imagePath)){
                $slide->Export($imagePath, "jpg", $width, $height);
            }

        }
        $presentation->Close();
        $powerpnt->Quit();
        $powerpnt = null;
    }

    public function addHeaderAndFooter($textHeader,$textFooter){

        $sections = $this->phpWord->getSections();

        $section = $sections[0];
        $header = $section->addHeader();

        $fStyle = [
            'size'=>11,
            'color'=>'blue',
            'bold'=>true
        ];

        $pStyle = [
            'alignment'=>\PhpOffice\PhpWord\SimpleType\Jc::CENTER
        ];

        $header->addText($textHeader, $fStyle, $pStyle);

        $footer = $section->addFooter();
        $footer->addText($textFooter, $fStyle, $pStyle);
    }

    /**
     * 获取表格节点内容
     * @param $node
     * @return string
     */
    public static function getTableNode($node)
    {
        $return = '';
        //处理行
        if ($node instanceof \PhpOffice\PhpWord\Element\Row) {
            foreach ($node->getCells() as $ele)
            {
                $return .= self::getTableNode($ele);
            }
        }
        //处理列
        else if ($node instanceof \PhpOffice\PhpWord\Element\Cell) {
            foreach ($node->getElements() as $ele)
            {
                $return .= self::getTextNode($ele);
            }
        }
        return $return;
    }

    public static function getTextNode($node)
    {
        $return = '';
        //处理文本
        if ($node instanceof \PhpOffice\PhpWord\Element\Text)
        {
            $return .=mb_convert_encoding($node->getText(), 'GBK', 'UTF-8');
        }
        //处理图片
        else if ($node instanceof \PhpOffice\PhpWord\Element\Image)
        {
            $return .= self::pic2text($node);
        }
        //处理文本元素
        else if ($node instanceof \PhpOffice\PhpWord\Element\TextRun) {
            foreach ($node->getElements() as $ele) {
                $return .= self::getTextNode($ele);
            }
        }
        return $return;
    }
}
